import random

import numpy as np
import math
import matplotlib.pyplot as plt
from PIL import Image


def jiasaw_transform(image, count=4):
    width, height = image.size
    item_width = int(width / count)
    item_height = int(height / count)
    patch_list = []

    for j in range(0, count):
        for i in range(0, count):
            box = (i * item_width, j * item_height, (i + 1) * item_width, (j + 1) * item_height)
            patch = image.crop(box)
            patch_list.append(patch)

    return patch_list


def cancat_image(patch_list, shuffle=True):
    if shuffle:
        random.shuffle(patch_list)
    np_matrix = np.array([np.array(patch) for patch in patch_list])
    count = int(math.sqrt(np_matrix.shape[0]))
    img_list = []
    for i in range(count):
        img = np.concatenate(np_matrix[i*count:(i+1)*count],1)
        img_list.append(img)
    img = np.vstack(img_list)
    return img


if __name__ == '__main__':
    img = Image.open('./linboli.jpg')
    list = jiasaw_transform(img)
    result = cancat_image(list)
    plt.imshow(result)
    plt.show()
